package com.test;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class main extends Activity {
    private static final String TAG = "verbose";

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        InputStream in = null;
        	
        HttpClient client = new DefaultHttpClient();
            try {
            	
            	// Creating client and a post

                HttpPost request = new HttpPost();

                //configure post
                request.setHeader("client", "Client connected");
                request.setURI(new URI("http://127.0.0.1:8080/0"));

                Log.v(TAG, "post configured");

                //excecute post from client
                HttpResponse response = client.execute(request);
                Log.v(TAG, "post executed");
                
                //read server response                
                in = response.getEntity().getContent();
                Log.v(TAG,"available data " + in.available());
                
                // receive file
                int bytesRead;
                int current = 0;

                //amount of bytes the file is... this is just hardcoded
                byte [] mybytearray  = new byte [4096*2];

 

                File root = Environment.getExternalStorageDirectory();

      	      	File myFile = new File (root + "/" + "source-copy.txt");

                if(!myFile.exists()){
                	myFile.createNewFile();
                	Log.v(TAG,"file crated");
                }
                
                FileOutputStream fos = new FileOutputStream(root + "/" + "source-copy.txt");

                
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = in.read(mybytearray,0,mybytearray.length);
                current = bytesRead;

            	Log.v(TAG,"file received");

            	
            	//Reversing the bytes
                do {
                   bytesRead =
                      in.read(mybytearray, current, (mybytearray.length-current));
                   if(bytesRead >= 0) 
                	   current += bytesRead;
                } while(bytesRead > -1);
                
            	Log.v(TAG,"wrote data to file");


                bos.write(mybytearray, 0 , current);
                bos.flush();
                bos.close();

                in.close();

            } catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				client.getConnectionManager().shutdown();        
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


        
        
        
		// Httpclient handeling with java.net.HttpURLConnection.
		// Both uploading and downloading from server.
			
//        try{
//            URL url=new URL("http://192.168.0.100:8081");
//            HttpURLConnection con;
//            con=(HttpURLConnection)url.openConnection();
//            Log.v(TAG,"Connection opened");
//            con.setDoInput(true);
//            con.setDoOutput(true);
//            con.setRequestMethod("POST");
//            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            con.setRequestProperty("Accept", "application/octet-stream");
//            Log.v(TAG,"Post configured");
//            DataOutputStream dos=new DataOutputStream(con.getOutputStream());
//            dos.writeUTF("From Client");
//            int status = con.getResponseCode();
//            Log.v(TAG,"Post executed");
//            if(status == 200){
//                DataInputStream response = new DataInputStream(con.getInputStream());
//                Log.v(TAG, response.readUTF());
//            }
//            dos.flush();
//            dos.close();
//            Log.v(TAG,"Finish try");
//        }
//        catch(Exception e){
//            Log.v(TAG,"Exception"+e);
//        }  
			

    }
}